// useFather.ts
import { ref, onUnmounted } from 'vue';
import emitter from '@/utils/emitter';

// 父组件的状态和方法,进行暴露
export function useFather() {
    const cake = ref('蛋糕1');
    const toy = ref('');
    const computer = ref('');
    // 绑定事件
    const FatherbindEvents = () => {
        emitter.on('send-toy-tofather', (value: any) => {
            toy.value = value;
        });

        emitter.on('send-computer-tofather', (value: any) => {
            computer.value = value;
        });
    };
    //
    // 卸载时解绑事件
    onUnmounted(() => {
        emitter.off('send-toy-tofather');
        emitter.off('send-computer-tofather');
    });
    // 公开数据和方法
    return {
        cake,
        toy,
        computer,
        FatherbindEvents,
    };
}

//ChildDemo1组件,使用子组件进行通信
export function useChildDemo1(){
    //数据
    let toy=ref("奥特曼")
    let computer=ref("")
    let fathercake=ref("")
    //绑定事件
    const Child1bindEvents = () => {
        // 给emitter绑定send-computer事件
       emitter.on('send-computer', (value: any) => {
           computer.value = value
       });
      // 给emitter绑定send-cake-tochild1事件
      emitter.on('send-cake-tochild1', (value: any) => {
        fathercake.value = value
      });
    };
    // 在组件卸载时解绑send-cake-tochild1事件
    onUnmounted(() => {
        emitter.off('send-cake-tochild1')
	    emitter.off('send-computer')
    })
    // 公开数据和方法
    return {
        toy,
        computer,
        fathercake,
        Child1bindEvents
    } 
}

//ChildDemo2组件,使用子组件进行通信
export function useChildDemo2(){
    // 数据
    let computer = ref('联想')
    let toy = ref('')
    let fathercake = ref('')
    // 绑定事件
    const Child2bindEvents = () => {
       // 给emitter绑定send-toy事件
       emitter.on('send-toy', (value: any) => {
            toy.value = value
        });
        // 给emitter绑定send-cake-tochild2事件
        emitter.on('send-cake-tochild2', (value: any) => {
            fathercake.value = value
        });    
    };
    // 在组件卸载时解绑send-cake-tochild2事件
    onUnmounted(() => {
        emitter.off('send-cake-tochild2')
        emitter.off('send-toy')
    })
    // 公开数据和方法
    return {
        computer,
        toy,
        fathercake,
        Child2bindEvents
    }
}